<template>
  <div class='q-pa-md'>
    <q-table
      v-model:pagination='pagination'
      :columns='columns'
      :filter='filter'
      :loading='loading'
      :rows='rows'
      binary-state-sort
      row-key='id'
      title='Treats'
      @request='onRequest'
    >
      <template v-slot:top-left>
        <div class='topSpan'>
          <span>编号：</span>
          <span>{{serveNo}}</span>
        </div>
        <div class='row'>
          <div class='col-4' style='min-width: 250px; max-width: 300px' @mouseover='mouseover'>
            <q-select
              v-model='mulSelect.arr'
              filled
              label='选择项'
              multiple
              name='search'
              stack-label
              use-chips
            />
          </div>
          <div class='col-2'>
            <q-btn color='white' icon='search' text-color='black' @click='fetchFromServer' />
          </div>
        </div>

        <div class='q-pt-md row justify-start items-center'>

          <div v-for='(item,index) in searchFrame' :key='index' class='q-px-md'>
            <div v-if='item.entity_code=="701" && item.property_code=="createDate"' class='q-pa-md' >
              <q-btn color='primary' :label='item.property_name' @click='qdateShow=true' />
              <div>
                <q-date v-model='qdateModel' range v-show='qdateShow' @range-end='qdateClick(item,index)'
                        style='position:absolute;top: 140px;left: 47px;z-index: 100' />
              </div>
            </div>

            <q-btn-dropdown :label='item.property_name' class='col-4' color='primary' v-else
                            @click='onQueryBar(index+1)'>
              <q-list v-for='item in searchFrameArr' :key='index'>
                <q-item v-close-popup clickable @click='searchClick(item,index)'>
                  <q-item-section>
                    <q-item-label>
                      {{item.eventName}}
                    </q-item-label>
                  </q-item-section>
                </q-item>
              </q-list>
            </q-btn-dropdown>



          </div>
        </div>
      </template>

      <template v-slot:top-right>
        <q-btn class='control-btn' color='primary' label='类型' @click='toType' />
        <q-btn v-for='(item,index) in globalOperation' :key='index' :label='item.operateEventName' class='control-btn'
               color='primary' @click='toAdd(item)' />
      </template>

      <template v-slot:header='props'>
        <q-tr :props='props'>
          <template
            v-for='col in props.cols'
            :key='col.name'
            :props='props'
          >
            <template v-if='col.name == "control"'>
              <q-th align='left' class='sticky-col'>
                {{ col.label }}
              </q-th>
            </template>
            <template v-else-if='col.name == "detail"'>
              <q-th align='left' class='sticky-col'>
                {{ col.label }}
              </q-th>
            </template>
            <template v-else-if='col.name == "subject"'>
              <q-th align='left' class='sticky-col'>
                {{ col.label }}
              </q-th>
            </template>
            <template v-else>
              <q-th align='left'>
                {{ col.label }}
              </q-th>
            </template>
          </template>
        </q-tr>
      </template>
      <template v-slot:body='props'>
        <q-tr :props='props'>
          <template
            v-for='col in props.cols'
            :key='col.name'
            :props='props'>
            <template v-if='col.name == "control"'>
              <q-td class='sticky-col'>
                <q-btn-dropdown
                  :label='operationFirstSelections.operateEventName'
                  split
                  @click='topOperation(props.row,operationFirstSelections)'
                >
                  <q-list v-for='(item, index) in operationSelections' :key='index'>
                    <q-item v-close-popup clickable @click='topOperation(props.row,item)'>
                      <q-item-section>
                        <q-item-label>{{ item.operateEventName }}</q-item-label>
                      </q-item-section>
                    </q-item>
                  </q-list>
                </q-btn-dropdown>
              </q-td>
            </template>
            <template v-else-if='col.name == "detail"'>
              <q-td class='sticky-col'>
                <q-btn color='primary' label='详情' @click='toDetail(props.row)' />
              </q-td>
            </template>
            <template v-else-if='col.name == "subject"'>
              <q-td class='sticky-col'>
                <q-btn-dropdown
                  :label='relationFirstSelection.arr.relationName'
                  split
                  @click='toRelation(props.row,relationFirstSelection.arr)'
                >
                  <q-list v-for='(item, index) in relationSelection.arr' :key='index'>
                    <q-item v-close-popup clickable @click='toRelation(props.row,item)'>
                      <q-item-section>
                        <q-item-label>{{ item.relationName }}</q-item-label>
                      </q-item-section>
                    </q-item>
                  </q-list>
                </q-btn-dropdown>
              </q-td>
            </template>
            <template v-else-if='col.name == "serveNo"'>
              <q-td>
                {{col.value}}
              </q-td>
            </template>
            <template v-else>
              <q-td>
                {{ col.value }}
              </q-td>
            </template>
          </template>
        </q-tr>
      </template>
    </q-table>
  </div>
</template>
<script lang='ts'>
import { Operation, OriginalRows, Pagination, Props, recOperation, TableColumn } from 'src/components/models';
import { defineComponent, onMounted, reactive, ref } from 'vue';
import { getRequest, postRequest } from 'src/components/functions';
import { useStore } from 'src/store';
import { CarMessage, cartypeRelation } from 'src/store/sphinx/state';
import { useRoute, useRouter } from 'vue-router';

export default defineComponent({
  name: 'TableComponent',
  setup(props) {
    let rote = useRoute();
    let router = useRouter();
    const store = useStore();
    const queryMenu = 'channel/channel/queryMenu';
    const getInterface = '/channel/channel/getInterface';
    const userData = store.state.sphinx.userData;
    let columns = ref<TableColumn[]>();
    let operationFirstSelections = ref<recOperation>();
    let operationSelections = ref<recOperation[]>();
    let globalOperation = ref<recOperation[]>();
    const originalRows = ref<OriginalRows[]>();
    const rows = ref([]);
    const filter = ref<string>();
    const loading = ref<boolean>(true);
    const pagination = ref<Pagination>({
      sortBy: 'desc',
      descending: false,
      page: 1,
      rowsPerPage: 10,
      rowsNumber: 10
    });
    let entityCode = ref<string>('');
    let childCode = ref<string>('');
    let fromdataUrl = ref<string>('');
    let searchFrame = ref([]);
    let searchFrameArr = ref([]);
    let mulSelect = reactive({ arr: [] });
    let QueryBarCode = reactive({ arr: [] });
    let relationFirstSelection = reactive({ arr: [] });
    let relationSelection = reactive({ arr: [] });
    let qdateShow = ref<boolean>(false);
    let qdateModel = ref({ from: '', to: '' });
    let serveNo = rote.query.serveNo

    //点击下拉的数据展示在搜索框里
    function searchClick(item: any, index: number) {
      let itemElement = searchFrame.value[index].property_code;
      mulSelect.arr.push(item.eventName);
      let obj = {};
      obj[itemElement] = item.eventName;
      QueryBarCode.arr.push(obj);
      mulSelect.arr = Array.from(new Set(mulSelect.arr));
      console.log(QueryBarCode.arr);
    }

    //点击日期数据展示在搜索框里
    function qdateClick(item:any,index:number){
      let itemElement = searchFrame.value[index].property_code;
      let time=qdateModel.value.from+' '+qdateModel.value.to
      let newTime = time.replace(/\//g,'-')
      mulSelect.arr.push(newTime);
      let obj = {};
      obj[itemElement] = newTime;
      QueryBarCode.arr.push(obj);
      mulSelect.arr = Array.from(new Set(mulSelect.arr));
      qdateShow.value=false;
      console.log(QueryBarCode.arr);
    }


    // 点击搜索框获取数据
    function onQueryBar(i) {
      //获取搜索数据的接口
      let resData = {
        entityCode: entityCode.value,
        entityType: childCode.value + '1070' + i,
        theirEventCode: '001'
      };
      let QueryBarUrl = ref<string>('');
      let QueryBarOption = ref<string>('');
      postRequest(getInterface, resData, res => {
        // let url=res.data.interfaceEnglish;
        // QueryBarUrl.value=url.substr(url.indexOf('/')+1)
        let url=res.data.interfaceEnglish;
        QueryBarOption.value=url.substr(0,url.indexOf('/'))
        QueryBarUrl.value=url.substr(url.indexOf('/')+1)
      });

      //获取搜索条件
      let resData1 = {
        entityCode: entityCode.value,
        entityType: childCode.value,
        sceneCodeType: '101102' + userData.roleType + '103',
        objectCodeType: '1070' + i
      };
      let QueryBarData = ref({});
      postRequest(queryMenu, resData1, res => {
        res.forEach(i => {
          let obj = {};
          obj[i.property_code] = '';
          QueryBarData.value = obj;
        });
      });

      //获取搜索数据
      searchFrameArr.value = [];
      setTimeout(() => {
        let red = {
          entityCode: entityCode.value,
          entityType: ''
        }
        if(QueryBarOption.value=='get'){
          getRequest(QueryBarUrl.value,data=>{
            searchFrameArr.value = data;
          },red)
        }if(QueryBarOption.value=='post'){
          postRequest(QueryBarUrl.value, red, (data) => {
            searchFrameArr.value = data;
          });
        }
      }, 1000);
    }

    // 鼠标放在搜索框上出搜索选项
    function mouseover() {
      let resData = {
        entityCode: entityCode.value,
        entityType: '99',
        sceneCodeType: '101102' + userData.roleType + '103',
        objectCodeType: '107'//代表搜索的代码
      };
      if (searchFrame.value.length == 0) {
        postRequest(queryMenu, resData, (res: []) => {
          searchFrame.value = res;
        });
      }
    }

    //去往类型页面
    function toType() {
      if (entityCode.value !== undefined) {
        void router.push('/Type?entityCode=' + entityCode.value + '&childCode=' + childCode.value + '00');
      }
    }

    // 存储数据
    function setUserDetail(data: CarMessage) {
      store.commit('sphinx/updateCarstate', data);
    }

    // 去往详情页面
    function toDetail(p: any) {
      setUserDetail(p);//将这一行的详细信息存储在vuex
      if (entityCode.value !== undefined) {
        void router.push('/Detail?entityCode=' + entityCode.value + '&childCode=' + childCode.value);
      }
    }

    //操作项的第一个选项
    function topOperation(p: any, item: any) {
      // console.log('item',item);
      // console.log('传过去的数据', p);
      setUserDetail(p);
      if (entityCode.value !== undefined) {
        void router.push('/Option?entityCode=' + entityCode.value + '&childCode=' + childCode.value + '&operateEvent=' + item.operateEvent);
      }
    }

    function toAdd(item) {
      // console.log(item);
      if (entityCode.value !== undefined) {
        void router.push('/Add?entityCode=' + entityCode.value + '&childCode=' + childCode.value + '&operateEvent=' + item.operateEvent);
      }
    }

    // 去往关系页面
    function toRelation(p: any, item: cartypeRelation) {
      setUserDetail(p);
      store.commit('sphinx/updateRelation', item);
      if (entityCode.value !== undefined) {
        void router.push('/Relation?entityCode=' + entityCode.value + '&childCode=' + childCode.value);
      }
    }

    // 获取关联主体的关系项
    function getRelation() {
      let reqData = reactive({});
      if (entityCode.value !== undefined) {
        reqData = {
          entityCode: entityCode.value,
          entityType: childCode.value,
          sceneCodeType: '101102' + userData.roleType + '103',//渠道101+当事人102+用户角色userData.roleType（例：01为管理员）+场景主体
          objectCodeType: '301'
        };
        postRequest('channel/channel/relation', reqData, res => {
          let arr = [];
          arr = res;
          relationFirstSelection.arr = arr.splice(0, 1)[0];
          relationSelection.arr = arr;
        });
      }
    }

    /**s
     * 请求主体首页表头
     */
    function requestColumns() {
      let reqData = reactive({});
      if (entityCode.value != undefined) {
        reqData = {
          entityCode: entityCode.value,
          entityType: '99',
          sceneCodeType: '101102' + userData.roleType + '103',
          objectCodeType: '102',//主体首页表头
        };
      }
      postRequest(queryMenu, reqData, getColums);
    }

    /**
     * 设置列名
     * @param resultData
     */
    function getColums(resultData: TableColumn[] | any) {
      let newArr = [];
      if (resultData !== undefined && resultData !== null && resultData.length > 0) {
        resultData.forEach(item => {
          newArr.push({
            name: item.property_code,
            label: item.property_name,
            field: item.property_code });
        });
        newArr.unshift({
          name: 'detail',
          label: '详情',
          field: 'detail'
        });
        newArr.push(
          {
            name: 'subject',
            label: '相关主体',
            field: 'subject'
          });
      }
      columns.value = newArr;
    }

    let fromdataOption=ref<string>('');
    // 获取请求表内数据的接口
    function getFromdataUrl() {
      let data = {
        entityCode: entityCode.value,
        entityType:'99',
        theirEventCode: '001' //查询
      };
      postRequest(getInterface, data, res => {
        let url=res.data.interfaceEnglish;
        fromdataOption.value=url.substr(0,url.indexOf('/'))
        fromdataUrl.value=url.substr(url.indexOf('/')+1)
      });
    }

    /**
     * 请求表内数据
     * @param startRow
     * @param count
     * @param filter
     * @param sortBy
     * @param descending
     */
    function fetchFromServer(startRow: number, count: number, filter: string, sortBy: string, descending: boolean) {
      //处理搜索内容的数据
      let newArr = ref([]);
      QueryBarCode.arr.forEach(x => {
        mulSelect.arr.forEach(y => {
          if (y == Object.values(x)[0]) {
            newArr.value.push(x);
          }
        });
      });
      let target = reactive({ companyId: '',serveNo:rote.query.serveNo });
      if (newArr.value.length != 0) {
        newArr.value.forEach(item => {
          Object.assign(target, item);
        });
      }
      target.companyId = userData.companyId;
      if(fromdataOption.value=='get'){
        getRequest(fromdataUrl.value,data=>{
          searchFrame.value.length = 0;
          // mulSelect.arr.length = 0;
          rows.value = data;
          loading.value = false;
        },target)
      }if(fromdataOption.value=='post'){
        // alert(target.serveNo);
        postRequest(fromdataUrl.value, target, (data) => {
          searchFrame.value.length = 0;
          // mulSelect.arr.length = 0;
          rows.value = data;
          loading.value = false;
        });
      }
    }

    /**
     * 计算分页
     * @param filter
     */
    function getRowsNumberCount(filter: string): number {
      let count = 0;
      if (originalRows.value !== undefined) {
        if (!filter) {
          return originalRows.value.length;
        }
        originalRows.value.forEach((treat: OriginalRows) => {
          if (treat.name.includes(filter)) {
            ++count;
          }
        });
      }
      return count;
    }

    /**
     * 数据请求
     * @param props
     */
    function onRequest(props: Props) {
      const { page, rowsPerPage, sortBy, descending } = props.pagination;
      const filter = props.filter;
      // emulate server
      setTimeout(() => {
        // update rowsCount with appropriate value
        pagination.value.rowsNumber = getRowsNumberCount(filter);
        // get all rows if "All" (0) is selected
        const fetchCount = rowsPerPage === 0 ? pagination.value.rowsNumber : rowsPerPage;
        // calculate starting row of data
        const startRow = (page - 1) * rowsPerPage;
        // fetch data from "server"
        fetchFromServer(startRow, fetchCount, filter, sortBy, descending);
        // clear out existing data and add new
        // don't forget to update local pagination object
        pagination.value.page = page;
        pagination.value.rowsPerPage = rowsPerPage;
        pagination.value.sortBy = sortBy;
        pagination.value.descending = descending;
        // ...and turn of loading indicator
      }, 200);
    }





    /**
     * 通过地址栏获取传来的实体代码entityCode
     */
    function setApiByInterfaceEnglish() {
      entityCode.value = <string>rote.query.entityCode;
      childCode.value = <string>rote.query.childCode;
      if (childCode.value === undefined) {
        childCode.value = '';
      }
    }

    /**
     * 组合请求
     */
    function requestTableData() {
      setApiByInterfaceEnglish();
      requestColumns();
      getFromdataUrl();
      // get initial data from server (1st page)
      onRequest({
        pagination: pagination.value,
        filter: ''
      });
      getRelation();
    }


    onMounted(() => {
      requestTableData();
    });

    return {
      filter,
      loading,
      pagination,
      columns,
      rows,
      operationFirstSelections,
      operationSelections,
      globalOperation,
      onRequest,
      toType,
      entityCode,
      toDetail,
      toAdd,
      toRelation,
      topOperation,
      getFromdataUrl,
      fromdataUrl,
      mouseover,
      searchFrame,
      onQueryBar,
      searchFrameArr,
      mulSelect,
      searchClick,
      fetchFromServer,
      childCode,
      userData,
      relationFirstSelection,
      relationSelection,
      fromdataOption,
      qdateShow,
      qdateModel,
      qdateClick,
      serveNo
    };
  }
});
</script>
<style scoped>
  .topSpan {
    margin-bottom: 30px;
  }
</style>
